# -*- coding: utf-8 -*-
import random
import scrapy
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from zc_core.dao.sku_dao import SkuDao
from zc_core.dao.sku_pool_dao import SkuPoolDao
from zc_core.model.items import Box
from zc_core.util.http_util import retry_request
from zc_core.spiders.base import BaseSpider
from changsha.rules import *


class OrderSpider(BaseSpider):
    name = 'order'
    # 常用链接
    order_list_url = 'http://hunan.gpmart.cn/productsdetail/ajaxPagerForProductInfo.action?productId={}&pageIndex={}&pageSize={}'
    default_page_size = 100
    # 覆盖配置
    custom_settings = {
        'DOWNLOAD_DELAY': 0
    }

    def __init__(self, batchNo=None, *args, **kwargs):
        super(OrderSpider, self).__init__(batchNo=batchNo, *args, **kwargs)

    def start_requests(self):
        # sku_list = SkuDao().get_batch_sku_list(self.batch_no, fields={'_id': 1, 'supplierId': 1})
        sku_list = SkuPoolDao().get_sku_pool_list()
        self.logger.info('批次商品：%s' % len(sku_list))
        random.shuffle(sku_list)
        for sku in sku_list:
            sku_id = sku.get('_id')
            supplier_id = sku.get('supplierId')

            # 采集第一页订单
            page = 1
            yield Request(
                method='POST',
                url=self.order_list_url.format(sku_id, page, self.default_page_size),
                callback=self.parse_order_item,
                errback=self.error_back,
                meta={
                    'batchNo': self.batch_no,
                    'skuId': sku_id,
                    'supplierId': supplier_id,
                    'page': str(page)
                },
                priority=210,
                dont_filter=True
            )

    # 处理sku列表
    def parse_order_item(self, response):
        meta = response.meta
        sku_id = meta.get('skuId')
        page = meta.get('page')
        # 处理订单
        orders = parse_order_item(response)
        if orders:
            self.logger.info('订单: sku=%s, cnt=%s' % (sku_id, len(orders)))
            yield Box('order_item', self.batch_no, orders)

            if len(orders) >= self.default_page_size:
                next_page = page + 1
                yield Request(
                    method='POST',
                    url=self.order_list_url.format(sku_id, next_page, self.default_page_size),
                    callback=self.parse_order_item,
                    errback=self.error_back,
                    meta={
                        'batchNo': self.batch_no,
                        'skuId': sku_id,
                        'supplierId': meta.get('supplierId'),
                        'page': str(next_page)
                    },
                    priority=210,
                    dont_filter=True
                )
        else:
            self.logger.info('无单: sku=%s' % sku_id)
